/**
 * @author yinyuejia
 * @file 主题，颜色配置
 */

import storage from '@/utils/storage';
import colorTool from '@/utils/color';
import themeConfig from '@/config/theme';

const defaultState = {
  size: 'default',
  zIndex: 3000,
  primary: '',
  bgColor: '',
  textColor: '',
  activeTextColor: '',
  sideBorderColor: '',
  key: themeConfig.defaultKey,
};
const storageKey = 'theme';

// 鼠标移动到菜单项上的背景色
const getMenuHoverBgColor = function (bgColor: any) {
  return colorTool.isDark(bgColor) ? colorTool.lighten(bgColor, 0.1) : '#ecf5ff';
};

// 当主题设置变化 改变html样式
const changeHtmlColor = function (color: any) {
  if (color.primary) {
    document.documentElement.style.setProperty('--el-color-primary', color.primary);
    for (let i = 1; i <= 9; i++) {
      document.documentElement.style.setProperty(
        `--el-color-primary-light-${i}`,
        colorTool.lighten(color.primary, i / 10),
      );
    }
    document.documentElement.style.setProperty('--el-color-primary-darken-1', colorTool.darken(color.primary, 0.1));
  }
  if (color.bgColor) {
    document.documentElement.style.setProperty('--el-bg-color-primary', color.bgColor);
    document.documentElement.style.setProperty('--el-menu-bg-color', color.bgColor);
    for (let i = 1; i <= 9; i++) {
      document.documentElement.style.setProperty(
        `--el-bg-color-primary-light-${i}`,
        colorTool.lighten(color.bgColor, i / 10),
      );
    }
  }
  if (color.bodyBgColor) {
    document.documentElement.style.setProperty('--el-body-bg-color', color.bodyBgColor);
  }
};
export default {
  state: defaultState,
  mutations: {
    /* eslint-disable */
    reload(this: any) {
      let data = storage.get(storageKey);
      this.commit('changeTheme', data && Object.keys(data).length > 0 ? data : { key: themeConfig.defaultKey });
    },
    /* eslint-enable */
    clear() {},
    changeTheme(state: any, payload: any) {
      let theme: any = {};
      if (payload.key) {
        theme = themeConfig.themes.find((a) => a.key === payload.key);
      }
      const req = { ...payload, ...(theme || {}) };
      Object.keys(defaultState).forEach((k) => {
        if (req[k] !== null && req[k] !== undefined) {
          state[k] = req[k];
          storage.set(`${storageKey}.${k}`, state[k]);
        }
      });
      changeHtmlColor(req);
    },
  },
  getters: {
    menuHoverBgColor(state: any) {
      return getMenuHoverBgColor(state.bgColor);
    },
  },
};
